package com.gim.util;

import connect.session.Session;
import envelope.EnvelopeOuterClass;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import user.User;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class NettyProtobufClient {

    private static final String SECRET_KEY = "anexamplekey1234"; // 16字节密钥用于AES
    private static final byte[] FIXED_IV = "addscs1212345221".getBytes(); // 16字节固定IV用于AES

    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 3000;

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new AcceptHandle());

            Channel ch = b.connect(host, port).sync().channel();

            // 创建Protobuf消息
            User.InitRequest initUser = User.InitRequest.newBuilder()
                    .setSessionId("1001").build();


            EnvelopeOuterClass.Envelope envelope = EnvelopeOuterClass.Envelope.newBuilder()
                    .setRouting("session")
                    .setPayload(initUser.toByteString())
                    .build();

            // 加密消息
            byte[] encryptedData = encryptData(envelope.toByteArray(), SECRET_KEY);

            // 发送加密数据
            ChannelFuture channelFuture = ch.writeAndFlush(Unpooled.wrappedBuffer(encryptedData));
            channelFuture.addListener((ChannelFuture future) -> {
                if (future.isSuccess()) {
                    System.out.println("Encrypted Protobuf message sent successfully");
                } else {
                    future.cause().printStackTrace();
                    System.out.println("Failed to send encrypted message");
                }
            });
            ch.closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    // AES加密方法 - 使用固定IV
    private static byte[] encryptData(byte[] data, String secretKey) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // 使用固定IV (16字节)
        IvParameterSpec ivSpec = new IvParameterSpec(FIXED_IV);

        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        return cipher.doFinal(data);
    }
}


